package com.heima.search.service.Imp;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.model.common.constants.es.EsIndexConstance;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService esService;
    @Value("${file.oss.web-site}")
    private String website;
    @Autowired
    private ApUserSearchService apUserSearchService;
    /**
     * 对索引库搜索查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDTO dto) {
        //1.参数校验 检验关键字
        if (StringUtils.isBlank(dto.getSearchWords())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"搜索的字段不能为空");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            dto.setUserId(user.getId() == null?null:user.getId());
        }
        //搜索行为进行保存
        apUserSearchService.insert(dto);
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getPageSize() <= 0) {
            dto.setPageSize(10);
        }
        //2.构建搜素条件 SearchBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2.1创建bool条件 用于组合其他查询的基础条件
        //创建bool条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //bool.must （按照关键词，进行match（分词查询））
        boolQuery.must(QueryBuilders.matchQuery("title",dto.getSearchWords()));
        //bool.filter (按照最小时间，进行range范围查询)
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        //2.2构建排序条件 按照发布时间降序排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);
        //2.3构建分页条件
        sourceBuilder.size(dto.getPageSize());
        //2.4构建高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);
        //3.执行搜索得到结果
        sourceBuilder.query(boolQuery);
        PageResponseResult result = esService.search(sourceBuilder, SearchArticleVO.class, EsIndexConstance.IndexName);
        //4.结果需要拼接前端的路径
       List<SearchArticleVO> list = (List<SearchArticleVO>) result.getData();
        for (SearchArticleVO searchArticleVO : list) {
            String images = searchArticleVO.getImages();
            if ( !StringUtils.isBlank(images)) {
                //将oss的图片路径拼接上去
                images = Arrays.stream(images.split(","))
                        .map(url->website + url)
                        .collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }
        }
        return result;
    }

    /**
     * 新增文章索引
     * @param article
     */
    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,EsIndexConstance.IndexName);
    }

    /**
     * 删除文章索引
     * @param articleId
     */
    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,EsIndexConstance.IndexName);
    }
}
